import axios from 'axios';
import {Message, MessageBox} from 'element-ui';
import store from '../store';
import {getToken} from '@/utils/auth';
import Qs from 'qs';
import router from '../router'
import {removeToken} from "./auth";


// 创建axios实例
const service = axios.create({
    // baseURL: 'http://47.96.125.159:8088/',
    // 政府接口，生产环境
    baseURL: 'http://orgovapi.dc.zjmade.cn/',
    // 政府接口，测试环境
    // baseURL: 'http://uatorgovapi.dc.zjmade.cn',
    timeout: 500000,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    transformRequest: [
        function (data) {
            const token = getToken() || localStorage.getItem('token');
            if (token != '') {
                if (data) {
                    data.token = token;
                } else {
                    data = {
                        token: token
                    };
                }

            }
            return Qs.stringify(data);
        }
    ]
});

// request拦截器
service.interceptors.request.use(
    config => {
        if (store.getters.token) {
            config.headers.token = getToken();
        }
        return config;
    },
    error => {
        // Do something with request error
        console.log(error); // for debug
        Promise.reject(error);
    }
);

// response 拦截器
service.interceptors.response.use(
    response => {
        /*
         * code为非0是抛错
         */
        const res = response.data;
        if (res.code !== 0) {
            Message({
                message: res.msg,
                type: 'error',
                duration: 5 * 1000
            });

            // 99: 用户登录过期，token无效; 9999: 服务内部错误，异常返回;
            // 99: 用户登录过期，token无效; 9999: 服务内部错误，异常返回; 999 权限不足
            if (res.code === 99) {
                MessageBox.confirm(
                    '你已被登出，可以取消继续留在该页面，或者重新登录',
                    '确定登出',
                    {
                        confirmButtonText: '重新登录',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    localStorage.clear();
                    sessionStorage.clear();
                    removeToken();
                    let returnUrl = `${router.options.base}login`
                    window.location.href = returnUrl
                    // router.replace({name:'Login'})
                    /*     store.dispatch('FedLogOut').then(() => {
                           // location.reload(); // 为了重新实例化vue-router对象 避免bug
                           this.$router.push({ path: '/login' });
                         });*/
                });
            } else if (res.code === 999) {
                // 权限不足
                Message({
                    message: res.msg,
                    type: 'error',
                    duration: 3 * 1000
                });
            } else if (res.code === 9999) {
                // 服务内部错误
                Message({
                    message: res.msg,
                    type: 'error',
                    duration: 3 * 1000
                });
            }
            return Promise.reject('error');
        } else {
            return response.data;
        }
    },
    error => {
        console.log('err' + error); // for debug
        Message({
            message: '服务繁忙，请稍后再试',
            type: 'error',
            duration: 5 * 1000
        });
        return Promise.reject(error);
    }
);

export default service;
